<script setup>
import { ref, reactive, onMounted } from 'vue';
import { positionApi } from '@T2/service/api.ts';
import { buildTree } from '@T2/utils/utils.ts';

const emits = defineEmits(['current-change', 'clear']);

onMounted(() => {
  getPosition();
});

const Resd = reactive({
  isActive: false,
  tree: [],
  value: null,
});
const getPosition = () => {
  Resd.tree = [];
  positionApi({
    method: 'get',
    params: {
      ordering: 'id',
    }
  }).then(res => {
    Resd.tree = buildTree(res.results || [], 'parent');
  });
}
const treeVisibleChange = (value) => {
  Resd.isActive = value;
}
const treeRef = ref(null);
const filterNode = (value, data, node) => {
  if (!value) {
    return true;
  }
  let obj = data, parentNode = node.parent, names = [];
  for(let level = node.level; level > 0; level--) {
    names = [...names, obj.name];
    obj = parentNode.data;
    parentNode = parentNode.parent;
  }
  return names.some(name => name.indexOf(value) !== -1);
}
const handleChange = (data, node) => {
  emits('current-change', data, node);
}
const handleClear = () => {
  let key = treeRef.value.getCurrentKey();
  if (key) {
    treeRef.value.setChecked(key, false, true);
  }
  emits('clear');
}
</script>

<template>
  <div :class="Resd.isActive ? 'filter-tree' : 'fold-tree'">
    <el-tree-select
      ref="treeRef"
      node-key="id"
      :fit-input-width="true"
      :teleported="false"
      filterable
      clearable
      check-strictly
      :highlight-current="true"
      :props="{label: 'name'}"
      v-model="Resd.value"
      :data="Resd.tree"
      :filter-node-method="filterNode"
      @visible-change="treeVisibleChange"
      @current-change="handleChange"
      @clear="handleClear"
    />
  </div>
</template>

<style lang="scss" scoped>
.filter-tree {
  width: 250px;
  transition: width 1s;
  margin-right: 20px;
  :deep(.el-icon.el-select__caret.el-select__icon) {
    display: inline-flex;
  }
}
.fold-tree {
  width: 40px;
  transition: width 1s;
  margin-right: 20px;
  :deep(.el-icon.el-select__caret.el-select__icon) {
    display: none;
  }
  :deep(.el-select__wrapper) {
    box-shadow: none;
  }
}
:deep(.el-select .el-select__wrapper) {
  padding-left: 35px;
  &.is-focused {
    box-shadow: none;
    &:hover {
      box-shadow: 0 0 0 1px #409eff inset;
    }
  }
  &::before {
    content: '';
    background: url('@T2/assets/common/search-black.png') no-repeat center;
    background-size: 100% 100%;
    position: absolute;
    width: 20px;
    height: 20px;
    left: 5px;
    top: 50%;
    transform: translateY(-50%);
  }
}
:deep(.el-select-dropdown) {
  .el-icon {
    font-size: 18px;
    margin-right: 5px;
  }
  .el-tree-node__content {
    height: 30px;
  }
  .el-select-dropdown__item {
    font-size: 15px;
  }
  .el-select-dropdown__wrap {
    max-height: 450px;
  }
}
</style>